package com.gmail.blackdog1987.carcare.util;

import android.content.Context;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * 双击感应器。
 * 
 * @author 周杰
 * @date 2013-4-15
 */
public class DoubleTapDetector {

	private static final int TAP = 0x00;

	private Context mContext;
	private long mDoubleTapTimeout = 2000L;
	private DoubleTapListener mDoubleTapListener;
	// private long mFirstTapTime;
	private String mTip = null;
	private Handler mHandler = new Handler();

	public DoubleTapDetector(Context context, DoubleTapListener doubleTapListener, String tip) {
		// mDoubleTapTimeout = ViewConfiguration.getDoubleTapTimeout();
		this.mContext = context;
		this.mDoubleTapListener = doubleTapListener;
		this.mTip = tip;
	}

	public boolean onKey(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mHandler.hasMessages(TAP)) {
				// if (SystemClock.currentThreadTimeMillis() - mFirstTapTime > mDoubleTapTimeout) {
				// mHandler.removeMessages(TAP);
				// } else {
				// mHandler.removeMessages(TAP);
				// mDoubleTapListener.doubleTap();
				// }
				mHandler.removeMessages(TAP);
				mDoubleTapListener.doubleTap();
			} else {
				// mFirstTapTime = SystemClock.currentThreadTimeMillis();
				Toast.makeText(mContext, mTip, Toast.LENGTH_SHORT).show();
				mHandler.sendEmptyMessageDelayed(TAP, mDoubleTapTimeout);
			}
		}
		return false;
	}

	public void cancel () {
		mHandler.removeMessages(TAP);
	}

	public interface DoubleTapListener {
		void doubleTap();
	}
}
